import shutil,os,subprocess
def set_squid_conf():
    '''
    backup squid.conf and cp this conf to /etc/squid
    '''
    squid_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'squid.conf')
    if os.path.exists('/etc/squid/squid.conf_bak'):
        if not os.path.exists('/etc/squid/squid.conf'):
            print('please check squid')
        else:
            shutil.copyfile(squid_path,'/etc/squid/squid.conf')
    elif os.path.exists('/etc/squid/squid.conf'):
        shutil.copyfile('/etc/squid/squid.conf','/etc/squid/squid.conf_bak')
        shutil.copyfile(squid_path,'/etc/squid/squid.conf')

def set_peers_conf(proxies,auth_proxies):
    '''
    cp peers conf to /etc/squid
    '''
    open_templete = 'cache_peer {IP} parent {PORT} 0 round-robin proxy-only no-query connect-fail-limit=2 name={name}\n'
    secret_templete = 'cache_peer {IP} parent {PORT} 0 login={username}:{password} round-robin proxy-only no-query connect-fail-limit=2 name={name}\n'

    with open('/etc/squid/peers.conf','wt')as f:
    # with open('peers.conf','wt')as f:
        for i, proxy in enumerate(auth_proxies):
            f.write(secret_templete.format(IP=proxy[0],PORT=proxy[1],username=proxy[2],password=proxy[3],name='auth_%s'%i))
        for i, proxy in enumerate(proxies):
            f.write(open_templete.format(IP=proxy[0],PORT=proxy[1],name='public_%s'%i))

def get_proxies():
    set_id = set()
    def duplicate_list(lis):
        if lis[0] in set_id:
            return False
        else:
            set_id.add(lis[0])
            return True

    ret_list = []
    auth_list = []

    # static
    static_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'static_proxy.csv')
    if os.path.exists(static_path):
        with open(static_path)as f:
            ret_list = list(map(lambda x:x.strip().split(':'),f.readlines()))

    auth_proxy = os.path.join(os.path.dirname(os.path.abspath(__file__)),'auth_proxy.csv')
    if os.path.exists(auth_proxy):
        with open(auth_proxy)as f:
            auth_list = list(map(lambda x:x.strip().split(':'),f.readlines()))

    return ret_list,auth_list

def config():

    set_squid_conf()
    proxies,auth_proxies = get_proxies()
    print(proxies)
    ps = []
    for each in proxies:
        try:
            ps.append('%s:%s'%(each[0],each[1]))
        except:
            pass

    set_peers_conf(proxies,auth_proxies)
    subprocess.run(["service","squid","reload"],check=True)

if __name__ == '__main__':
	config()

